package controller;

import model.Group;
import model.GroupDAO;
import model.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

@WebServlet("/getGroup")
public class GetGroupServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        try {
            int groupId = Integer.parseInt(request.getParameter("id"));
            GroupDAO groupDAO = new GroupDAO();
            Group group = groupDAO.getGroupById(groupId);

            response.setContentType("application/json");
            response.setCharacterEncoding("UTF-8");

            PrintWriter out = response.getWriter();
            if (group != null) {
                String jsonResponse = "{ \"group\": { \"id\": " + group.getId() + ", \"name\": \"" + group.getName() + "\" }, \"members\": [";
                List<User> members = group.getMembers();
                for (int i = 0; i < members.size(); i++) {
                    User member = members.get(i);
                    jsonResponse += "{ \"id\": " + member.getId() + ", \"name\": \"" + member.getName() + "\" }";
                    if (i < members.size() - 1) {
                        jsonResponse += ", ";
                    }
                }
                jsonResponse += "] }";
                out.print(jsonResponse);
            } else {
                out.print("{\"message\": \"小组不存在\"}");
            }
            out.flush();
        } catch (NumberFormatException e) {
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            response.getWriter().write("{\"message\": \"Invalid group ID\"}");
        } catch (Exception e) {
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            response.getWriter().write("{\"message\": \"服务器内部错误\"}");
        }
    }
}
